package maple.thelittleredbook.user.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import maple.thelittleredbook.common.dto.ApiResponse;
import maple.thelittleredbook.common.service.AuthService;
import maple.thelittleredbook.logging.annotation.SystemLog;
import maple.thelittleredbook.user.dto.UserDTO;
import maple.thelittleredbook.user.dto.UserUpdateRequestDTO;
import maple.thelittleredbook.user.service.UserService;

@Slf4j
@RestController
@RequestMapping("/api/users")
public class UserController {


    private final UserService userService;
    private final AuthService authService;

    @Autowired
    public UserController(UserService userService, AuthService authService) {
        this.userService = userService;
        this.authService = authService;
    }

    /**
     * 获取当前用户的个人信息
     * 直接从Spring Security上下文获取用户ID
     */
    @GetMapping("/me")
    @SystemLog(operation = "查看个人信息")
    public ResponseEntity<ApiResponse<UserDTO>> getMyProfile() {

        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        UserDTO userDTO = userService.getMyProfile(userId);
        return ResponseEntity.ok(ApiResponse.success("获取个人信息成功", userDTO));
    }

    /**
     * 根据用户ID查看用户信息（权限控制）
     * 一次性从Spring Security上下文获取用户信息
     */
    @GetMapping("/{userId}")
    @SystemLog(operation = "查看用户信息")
    public ResponseEntity<ApiResponse<Object>> getUserProfile(@PathVariable Long userId) {

        // 一次性获取当前用户信息
        Long currentUserId = authService.getCurrentUserId();
        String currentUserRole = authService.getCurrentUserRole();

        // 如果未登录，只能查看公开信息
        if (currentUserId == null) {
            currentUserId = -1L; // 设置为不可能的用户ID
            currentUserRole = "ANONYMOUS";
        }

        Object userInfo = userService.getUserProfile(userId, currentUserId, currentUserRole);
        return ResponseEntity.ok(ApiResponse.success("获取用户信息成功", userInfo));
    }

    /**
     * 更新用户个人信息
     * 直接从Spring Security上下文获取用户ID
     */
    @PutMapping("/me")
    @SystemLog(operation = "更新个人信息")
    public ResponseEntity<ApiResponse<UserDTO>> updateProfile(
            @Valid @ModelAttribute UserUpdateRequestDTO requestDTO) {

        Long userId = authService.getCurrentUserId();
        if (userId == null) {
            return ResponseEntity.ok(ApiResponse.fail("用户未登录或登录已过期"));
        }

        UserDTO userDTO = userService.updateUserProfile(
                userId,
                requestDTO.getUsername(),
                requestDTO.getBio(),
                requestDTO.getAvatar()
        );

        return ResponseEntity.ok(ApiResponse.success("更新个人信息成功", userDTO));
    }
}